package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 菜品
 */
@Slf4j
@RestController
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     */
    @PostMapping
    public Result addDish(@RequestBody DishDTO dishDTO) {
        log.info("前端增加菜品：{}", dishDTO);
        dishService.addDish(dishDTO);
        // 清理菜品缓存
        String key = "dish_" + dishDTO.getId();
        cleanCache(key);
        return Result.success();
    }

    /**
     * 菜品分页条件查询
     */
    @GetMapping("/page")
    public Result<PageResult> pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        log.info("前端传递的查询");
        PageResult page = dishService.pageQuery(dishPageQueryDTO);
        return Result.success(page);
    }

    /**
     * 批量删除菜品
     */
    @DeleteMapping
    public Result deleteDish(@RequestParam List<Long> ids) {
        log.info("前端要删除的菜品id：{}", ids);
        dishService.deleteDish(ids);
        cleanCache("dish_*");
        return Result.success();
    }

    /**
     * 根据 id 查询菜品
     */
    @GetMapping("/{id}")
    public Result<DishVO> selectById(@PathVariable Long id) {
        log.info("前端要回显的菜品id：{}", id);
        DishVO dishVO = dishService.selectById(id);
        return Result.success(dishVO);
    }

    /**
     * 修改菜品
     */
    @PutMapping
    public Result updateDish(@RequestBody DishDTO dishDTO) {
        log.info("前端要修改的菜品属性：{}", dishDTO);
        dishService.updateDish(dishDTO);
        cleanCache("dish_*");
        return Result.success();
    }

    /**
     * 菜品起售、停售
     */
    @PostMapping("status/{status}")
    public Result setDishStatus(@PathVariable Integer status, Integer id) {
        log.info("前端传递的状态参数：{}", status);
        dishService.setDishStatus(status, id);
        cleanCache("dish_*");
        return Result.success();
    }

    /**
     * 根据分类 id 查询菜品
     */
    @GetMapping("/list")
    public Result<List<Dish>> findDishByCategory(Long categoryId) {
        log.info("前端要分类查询的菜品：{}", categoryId);
        List<Dish> dishes = dishService.findDishByCategory(categoryId);
        return Result.success(dishes);
    }

    /**
     * 清理缓存数据统一方法
     */
    private void cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
